<?php

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use App\Models\Common\ApiResponse;
use App\Models\Invoice\GoodDetail;
use Illuminate\Http\Request;

class GoodDetailController extends Controller
{

    public $name = '发票商品';

    public function index()
    {
//        $this->admin = $user = admin();
        $parkingLotID = getParkingLotID();
//        $this->logContent = '查看发票商品列表';

        return ApiResponse::return('', GoodDetail::where('parking_lot_id', $parkingLotID)->get());
    }

    public function store(Request $request)
    {
        $this->admin = $user = admin();
        $this->parkingLotID = $parkingLotID = getParkingLotID();
        $this->logContent = '编辑发票商品';

        if ($id = $request->get('id')) {
            $goodDetail = GoodDetail::where('parking_lot_id', $parkingLotID)->findOrFail($id);
        } else {
            $goodDetail = new GoodDetail();
            $goodDetail->id = \Str::orderedUuid()->toString();
            $goodDetail->parking_lot_id = $parkingLotID;
        }

        $goodDetail->fill($request->only(['category', 'sn', 'name', 'tax_rate']));

        if (!in_array($goodDetail->category, [GoodDetail::CATEGORY_TMP_PAYMENT, GoodDetail::CATEGORY_MONTHLY_PAYMENT], true)) {
            return ApiResponse::fail('商品分类仅限月租和临停');
        }

        if (!$goodDetail->sn) {
            return ApiResponse::fail('商品编码不可为空');
        }

        if (!$goodDetail->name) {
            return ApiResponse::fail('商品名称不可为空');
        }

        $goodDetail->tax_rate = abs(floatval($goodDetail->tax_rate));

        if (GoodDetail::where('id', '<>', $goodDetail->id)->where('parking_lot_id', $parkingLotID)->where('sn', $goodDetail->sn)->exists()) {
            return ApiResponse::fail('商品编码不可重复');
        }

        if (GoodDetail::where('id', '<>', $goodDetail->id)->where('parking_lot_id', $parkingLotID)->where('category', $goodDetail->category)->exists()) {
            return ApiResponse::fail('商品分类已存在');
        }

        if ($goodDetail->save()) {
            return ApiResponse::return();
        }

        return ApiResponse::return('', null, ApiResponse::RESP_CODE_FAILURE);
    }

    public function show($id)
    {
//        $this->admin = $user = admin();
        $parkingLotID = getParkingLotID();
//        $this->logContent = '查看发票商品详情';
        $goodDetail = GoodDetail::where('parking_lot_id', $parkingLotID)->findOrFail($id);
        return ApiResponse::return('', $goodDetail);
    }


    public function destroy($id)
    {
        $this->admin = $user = admin();
        $this->parkingLotID = $parkingLotID = getParkingLotID();
        $this->logContent = '删除发票商品';

        if (GoodDetail::where('parking_lot_id', $parkingLotID)->where('id', $id)->delete()) {
            return ApiResponse::return();
        }
        return ApiResponse::return('', null, ApiResponse::RESP_CODE_FAILURE);
    }
}
